﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geometry;
using DevComponents.DotNetBar.SuperGrid;
using DevComponents.DotNetBar.SuperGrid.Style;
using PlanningGIS.Util.Log;
using PlanningGIS.ArcGIS.Custom;
using PlanningGIS.ArcGIS;
using PlanningGIS.Win.Controls;
using DevComponents.DotNetBar;

namespace PlanningGIS.Engine.Controls
{
    /// <summary>
    /// 图层属性表
    /// </summary>
    public partial class AttributeGridView : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public AttributeGridView()
        {
            InitializeComponent();
            RecordCount = 0;
            RecordSize = 1000;
            dgrdvwTable.PrimaryGrid.ShowRowGridIndex = true;
        }

        /// <summary>
        /// 获取或设置当前记录的索引号,从1开始
        /// </summary>
        private int _CurrentIndex = 0;

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int RecordCount { get; private set; }

        /// <summary>
        /// 获取选择的总数
        /// </summary>
        public int SelectCount { get; private set; }

        /// <summary>
        /// 获取或设置每次显示的记录条数
        /// </summary>
        public int RecordSize { get; set; }

        /// <summary>
        /// 获取数据源的名称
        /// </summary>
        public string SourceName { get; private set; }

        /// <summary>
        /// 获取当前绑定的图层,通过OnCreate赋值
        /// </summary>
        public IFeatureLayer BindLayer { get; private set; }

        /// <summary>
        /// 获取当前绑定的数据表,通过OnCreate赋值
        /// </summary>
        public ITable BindTable { get; private set; }

        /// <summary>
        /// 绑定的数据源
        /// </summary>
        private BindingManagerBase _BindManager = null;

        /// <summary>
        /// 获取或设置绑定的数据源管理对象
        /// </summary>
        public BindingManagerBase BindManager
        {
            get { return (_BindManager); }
            set
            {
                if (_BindManager != null)
                    _BindManager.PositionChanged -= BmPositionChanged;
                _BindManager = value;
                if (_BindManager != null)
                    _BindManager.PositionChanged += BmPositionChanged;
            }
        }

        /// <summary>
        /// 获取地图关联对象,通过OnCreate赋值
        /// </summary>
        public IHookHelper HookHelper { get; private set; }

        /// <summary>
        /// 设置关联的地图对象
        /// </summary>
        public object Hook
        {
            set
            {
                try
                {                    
                    if (value != null)
                    {
                        IActiveViewEvents_Event viewEvent = null;
                        if (HookHelper != null)
                        {
                            viewEvent = HookHelper.ActiveView as IActiveViewEvents_Event;
                            viewEvent.SelectionChanged -= MapSel_SelectionChanged;
                            HookHelper = null;
                        }
                        HookHelper = new HookHelper();
                        HookHelper.Hook = value;
                        viewEvent = HookHelper.ActiveView as IActiveViewEvents_Event;
                        viewEvent.SelectionChanged += MapSel_SelectionChanged;
                    }
                }
                catch
                {

                }
            }
        }

        /// <summary>
        /// 记录游标对象
        /// </summary>
        private ICursor _Cursor = null;

        /// <summary>
        /// 唯一主键的字段名称
        /// </summary>
        private string _OIDFieldName = "";

        /// <summary>
        /// 是否是地图选择
        /// </summary>
        private bool _IsMapSel = true;

        /// <summary>
        /// 选择的记录的唯一标识枚举
        /// </summary>
        private IEnumIDs _SelectedIDs = null;

        /// <summary>
        /// 显示所有的数据所得到的数据源
        /// </summary>
        private DataTable _SourceAll = null;

        /// <summary>
        /// 显示仅选择的数据所得到的数据源
        /// </summary>
        private DataTable _SourceSelection = null;
        
        /// <summary>
        /// 创建数据表对象
        /// </summary>
        /// <param name="featlyr">需要显示属性表的图层</param>
        /// <param name="filter">过滤条件</param>
        /// <returns></returns>
        public bool OnCreate(IFeatureLayer featlyr, IQueryFilter filter = null)
        {
            if (featlyr == null || !featlyr.Valid || featlyr.FeatureClass == null) return false;
            BindLayer = featlyr;
            return _ConvertLayer(filter);
        }

        /// <summary>
        /// 创建数据表对象
        /// </summary>
        /// <param name="featcls">需要显示属性表的要素类</param>
        /// <param name="filter">过滤条件</param>
        /// <returns></returns>
        public bool OnCreate(IFeatureClass featcls, IQueryFilter filter = null)
        {
            if (featcls == null) return false;
            BindLayer = new ESRI.ArcGIS.Carto.FeatureLayer();
            BindLayer.FeatureClass = featcls;
            BindLayer.Name = featcls.AliasName?? (featcls as IDataset).Name;
            return _ConvertLayer(filter);
        }

        /// <summary>
        /// 转换图层到数据表，尤其是关联图层
        /// </summary>
        /// <param name="filter">过滤条件</param>
        private bool _ConvertLayer(IQueryFilter filter = null)
        {
            if (BindLayer is IDisplayRelationshipClass)
            {
                IDisplayTable dsplytb = BindLayer as IDisplayTable;
                ITable tb = dsplytb.DisplayTable;
                return Create(dsplytb.DisplayTable, filter);
            }
            else
            {
                return Create(BindLayer.FeatureClass as ITable, filter);
            }
        }

        /// <summary>
        /// 构建属性表
        /// </summary>
        /// <param name="table">数据集对象</param>
        /// <param name="filter">过滤条件</param>
        /// <returns></returns>
        public bool Create(ITable table, IQueryFilter filter = null)
        {
            if (table == null) return false;
            btnAll.Checked = true;
            btnSel.Checked = false;
            BindTable = table;
            dgrdvwTable.PrimaryGrid.Rows.Clear();
            dgrdvwTable.PrimaryGrid.Columns.Clear();
            dgrdvwTable.PrimaryGrid.DataSource = null;
            _IsMapSel = true;
            try
            {
                SourceName = (table as IDataset).Name;
                _OIDFieldName = table.OIDFieldName;
                IField lenfd = null;
                IField areafd = null;
                try
                {
                    if(BindLayer != null)
                    {
                        lenfd = BindLayer.FeatureClass.LengthField;
                        if (BindLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                            areafd = BindLayer.FeatureClass.AreaField;
                    }
                }
                catch
                {

                }
                dgrdvwTable.AddColumns(table.Fields, lenfd, areafd);
                dgrdvwTable.PrimaryGrid.DataSource = null;
                _SourceAll = new DataTable(SourceName);
                _SourceAll.AddColumns(table.Fields);
                _SourceSelection = new DataTable(SourceName);
                _SourceSelection.AddColumns(table.Fields);
                RecordCount = table.RowCount(filter);
                _Cursor = table.Search(filter, false);
                InitSelection();
                dgrdvwTable.PrimaryGrid.DataSource = _SourceAll;
                BindManager = (_SourceAll != null) ? dgrdvwTable.BindingContext[_SourceAll.DefaultView] : null;
                AddAllRows();

                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                return false;
            }
            finally
            {

            }
        }

        /// <summary>
        /// 添加字段
        /// </summary>
        /// <param name="field"></param>
        public void AddField(IField field)
        {
            if (field == null && BindTable == null) return;
            BindTable.AddField(field);
            dgrdvwTable.AddColumn(field);
        }

        /// <summary>
        /// 选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwTable_SelectionChanged(object sender, GridEventArgs e)
        {
            _IsMapSel = false;
            if (btnSel.Checked)
            {
                //if (dgrdvwTable.PrimaryGrid.SelectedRowCount == 0) return;
                //IFeatureSelection sel = BindLayer as IFeatureSelection;
                //string w = "";
                //foreach (GridRow row in dgrdvwTable.PrimaryGrid.SelectedRows)
                //{
                //    w += " or " + _OIDFieldName + "=" + row.Cells[_OIDFieldName].Value.ToString();
                //}
                //w = w.Trim().Substring(2);
                //try
                //{
                //    IQueryFilter flt = new QueryFilter();
                //    flt.WhereClause = w;
                //    sel.SelectFeatures(flt, esriSelectionResultEnum.esriSelectionResultNew, true);
                //}
                //catch (Exception ex)
                //{
                //    LogHelper.WriteLog(ex);
                //}
                
            }
            _IsMapSel = true;
        }

        /// <summary>
        /// 地图选择改变
        /// </summary>
        void MapSel_SelectionChanged()
        {
            if (_IsMapSel)
            {
                InitSelection();
                if (btnSel.Checked)
                {
                    AddSelection();                    
                }
            }
            else
            {
                _IsMapSel = true;
            }
            SetDetial();
        }

        /// <summary>
        /// 初始化选择集
        /// </summary>
        private void InitSelection()
        {
            if (BindLayer == null || BindLayer.FeatureClass == null) return;
            if (_SelectedIDs != null)
            {
                Marshal.FinalReleaseComObject(_SelectedIDs);
                _SelectedIDs = null;
            }
            _SourceSelection.Clear();
            IFeatureSelection featsel = BindLayer as IFeatureSelection;
            _SelectedIDs = featsel.SelectionSet.IDs;
            SelectCount = featsel.SelectionSet.Count;
            
        }

        /// <summary>
        /// 滚动条滚动最大是继续加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwTable_ScrollMax(object sender, GridScrollEventArgs e)
        {
            try
            {
                if (e.ScrollEventArgs.Type == ScrollEventType.Last && _Cursor != null)
                {
                    btnNextPage_Click(null, null);
                }                
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            
        }

        /// <summary>
        /// 添加数据到列表行中
        /// </summary>
        /// <param name="index"></param>
        private void AddAllRows(int index = 0)
        {
            if (_Cursor == null) return;
            try
            {
                DataTable dt = dgrdvwTable.PrimaryGrid.DataSource as DataTable;
                dt.BeginLoadData();
                IRow feat = null;
                //this.Cursor = Cursors.WaitCursor;
                dgrdvwTable.PrimaryGrid.BeginDataUpdate();
                int idx = _CurrentIndex;
                while ((feat = _Cursor.NextRow()) != null)
                {
                    DataRow row = dt.NewRow();
                    for (int i = 0; i < feat.Fields.FieldCount; i++)
                    {
                        row[i] = feat.get_Value(i);
                    }
                    dt.Rows.Add(row);
                    row.AcceptChanges();
                    int count = dt.Rows.Count;                    
                    if ((count % RecordSize) == 0)
                    {
                        if ((index > 0 && count > index) || index == 0)
                        {
                            break;
                        }
                    }
                }
                dt.EndLoadData();
                dgrdvwTable.PrimaryGrid.EndDataUpdate();                
                if (dt.Rows.Count >= RecordCount)
                {
                    Marshal.FinalReleaseComObject(_Cursor);
                    _Cursor = null;
                }
            }
            finally
            {
                //this.Cursor = Cursors.Default;
            }
        }
        
        
        /// <summary>
        /// 添加选择的对象到列表中
        /// </summary>
        /// <param name="index"></param>
        private void AddSelection(int index = 0)
        {
            if (BindLayer == null) return;
            if (_SelectedIDs == null) return;
            if (_SourceSelection.Rows.Count == SelectCount) return;
            _SourceSelection.BeginLoadData();
            dgrdvwTable.PrimaryGrid.BeginDataUpdate();
            int id = 0;
            while ((id = _SelectedIDs.Next()) > -1)
            {
                DataRow row = _SourceSelection.NewRow();
                IFeature feat = BindLayer.FeatureClass.GetFeature(id);
                for (int i = 0; i < feat.Fields.FieldCount; i++)
                {
                    row[i] = feat.get_Value(i);
                }
                _SourceSelection.Rows.Add(row);
                row.AcceptChanges();
                int count = _SourceSelection.Rows.Count;
                if ((count % RecordSize) == 0)
                {
                    if ((index > 0 && count > index) || index == 0)
                    {
                        break;
                    }
                }
            }
            _SourceSelection.EndLoadData();
            dgrdvwTable.PrimaryGrid.EndDataUpdate();
            if (_SourceSelection.Rows.Count >= SelectCount)
            {
                Marshal.FinalReleaseComObject(_SelectedIDs);
                _SelectedIDs = null;
            }
        }

        /// <summary>
        /// 显示所有
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAll_Click(object sender, EventArgs e)
        {
            btnAll.Checked = true;
            btnSel.Checked = false;
            btnOrderAsc.Enabled = true;
            btnOrderDsc.Enabled = true;
            btnCancelOrder.Enabled = true;
            dgrdvwTable.PrimaryGrid.DataSource = _SourceAll;
            BindManager = (_SourceAll != null) ? dgrdvwTable.BindingContext[_SourceAll.DefaultView] : null;  
        }

        /// <summary>
        /// 仅显示已选择的
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSel_Click(object sender, EventArgs e)
        {
            btnAll.Checked = false;
            btnSel.Checked = true;
            btnOrderAsc.Enabled = false;
            btnOrderDsc.Enabled = false;
            btnCancelOrder.Enabled = false;
            dgrdvwTable.PrimaryGrid.DataSource = _SourceSelection;
            BindManager = (_SourceSelection != null) ? dgrdvwTable.BindingContext[_SourceSelection.DefaultView] : null;  
            AddSelection();
        }

        #region 遍历
        
        /// <summary>
        /// 第一个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirst_Click(object sender, EventArgs e)
        {
            _BindManager.Position = 0;
        }

        /// <summary>
        /// 上一个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrevious_Click(object sender, EventArgs e)
        {
            _BindManager.Position -= 1;
        }

        /// <summary>
        /// 下一个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNext_Click(object sender, EventArgs e)
        {
            _BindManager.Position += 1;
        }

        /// <summary>
        /// 最后一个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLast_Click(object sender, EventArgs e)
        {
            int count = RecordCount;
            if (btnSel.Checked)
                count = SelectCount;
            if (btnSel.Checked)
                AddSelection(count);
            else
                AddAllRows(count);
            _BindManager.Position = count - 1;
        }

        /// <summary>
        /// 跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtTurnTo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (string.IsNullOrWhiteSpace(txtTurnTo.Text)) return;
                int page = 0;
                if (int.TryParse(txtTurnTo.Text.Trim(), out page))
                {
                    int count = RecordCount;
                    if (btnSel.Checked)
                        count = SelectCount;
                    if (page >= count) page = count;
                    else if (page <= 1) page = 1;                    
                    if (btnSel.Checked)
                        AddSelection(page);
                    else
                        AddAllRows(page);
                    _BindManager.Position = page - 1;
                }
            }
            else if (Char.IsDigit(e.KeyChar) || e.KeyChar == 8)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        /// <summary>
        /// Updates out VCR control when the user
        /// moves position in the data collection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BmPositionChanged(object sender, EventArgs e)
        {
            _CurrentIndex = _BindManager.Position + 1;
            txtTurnTo.Text = _CurrentIndex.ToString();
            int count = RecordCount;
            if (btnSel.Checked)
                count = SelectCount;
            btnFirst.Enabled = (_CurrentIndex > 1 && count > 1);
            btnPrevious.Enabled = (_CurrentIndex > 1 && count > 1);
            btnNext.Enabled = count > _CurrentIndex;
            btnLast.Enabled = count > _CurrentIndex;
            txtTurnTo.Enabled = count > 1;
            txtTurnTo.Text = count > 0 ? _CurrentIndex.ToString() : "0";
            SetDetial();
            //((GridContainer)dgrdvwTable.PrimaryGrid.Rows[CurrentIndex - 1]).EnsureVisible(true);
            //((GridContainer)dgrdvwTable.PrimaryGrid.Rows[CurrentIndex - 1]).SetActive(true);
        }

        /// <summary>
        /// 设置记录的详细信息
        /// </summary>
        private void SetDetial()
        {
            lblStatus.Text = string.Format("（选中{0}共{1}条）",SelectCount, RecordCount);
        }
       
        #endregion

        #region  定位
        /// <summary>
        /// 当前行
        /// </summary>
        private GridRow _CurrentRow = null;
        /// <summary>
        /// 点击行标题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwTable_RowHeaderClick(object sender, GridRowHeaderClickEventArgs e)
        {
            if (e.MouseEventArgs.Button == System.Windows.Forms.MouseButtons.Right)
            {
                _CurrentRow = (GridRow)e.GridRow;
                cntMenus.SetContextMenuEx(dgrdvwTable, btnRowHeader);
            }
        }

        /// <summary>
        /// 双击行标题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwTable_RowHeaderDoubleClick(object sender, GridRowHeaderDoubleClickEventArgs e)
        {
            if (e.GridRow != null && e.GridRow.Index >= 0)
            {
                ZoomFeature(zjgisZoomType.ZoomTo, (GridRow)e.GridRow);
            }
        }

        /// <summary>
        /// 闪烁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFlash_Click(object sender, EventArgs e)
        {
            ZoomFeature(zjgisZoomType.Flash, _CurrentRow);
        }

        /// <summary>
        /// 平移到
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPanTo_Click(object sender, EventArgs e)
        {
            ZoomFeature(zjgisZoomType.PanTo, _CurrentRow);
        }

        /// <summary>
        /// 缩放到
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZoomTo_Click(object sender, EventArgs e)
        {
            ZoomFeature(zjgisZoomType.ZoomTo, _CurrentRow);
        }

        /// <summary>
        /// 定位的空间对象
        /// </summary>
        /// <param name="zoomtype"></param>
        /// <param name="row"></param>
        private void ZoomFeature(zjgisZoomType zoomtype, GridRow row)
        {
            if (BindLayer == null || HookHelper == null) return;
            IFeatureClass featcls = BindLayer.FeatureClass;
            if (featcls == null) return;
            try
            {
                string oidfd = featcls.OIDFieldName;
                GridCell cel = row.Cells.FirstOrDefault(t => t.GridColumn.Name.Equals(oidfd, StringComparison.CurrentCultureIgnoreCase) ||
                  t.GridColumn.Name.Equals((featcls as IDataset).Name + "." + oidfd, StringComparison.CurrentCultureIgnoreCase));
                if (cel == null) return;
                int oid = Convert.ToInt32(cel.Value);
                IFeature feat = featcls.GetFeature(oid);
                if (feat.Shape == null || feat.Shape.IsEmpty) return;
                IHookActions hookActions = HookHelper as IHookActions;
                if (hookActions == null) return;
                if (zoomtype == zjgisZoomType.ZoomTo)
                {
                    hookActions.DoAction(feat.Shape, esriHookActions.esriHookActionsZoom);
                    //HookHelper.ActiveView.Extent = geo.Envelope;
                    //HookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, HookHelper.ActiveView.Extent);
                }
                else if (zoomtype == zjgisZoomType.PanTo)
                {

                    hookActions.DoAction(feat.Shape, esriHookActions.esriHookActionsPan);
                    //IPoint pnt = new ESRI.ArcGIS.Geometry.Point();
                    //pnt.X = (feat.Shape.Envelope.XMin + feat.Shape.Envelope.XMax) / 2;
                    //pnt.Y = (feat.Shape.Envelope.YMax + feat.Shape.Envelope.YMin) / 2;
                    //(HookHelper.Hook as IMapControl3).CenterAt(pnt);
                }
                HookHelper.ActiveView.ScreenDisplay.UpdateWindow();//定位后在闪烁
                //DisplayHelper.DrawGeometryOnScreen(feat.Shape, HookHelper.ActiveView);
                //DisplayHelper.FlashGeometry(feat.Shape, HookHelper.Hook as IMapControl3);
                FlashHelper.FlashFeature(feat, HookHelper.Hook as IMapControl3);
            }
            catch (Exception ex)
            {
                ToastNotification.Show(this,"定位异常："+ex.Message,null,5 * 1000, eToastGlowColor.Blue, eToastPosition.BottomCenter);
            }
            
        }

        #endregion

        #region 清除右键
        /// <summary>
        /// 点击列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwTable_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                cntMenus.SetContextMenuEx(dgrdvwTable, null);
            }
        }

        #endregion

        #region 字段操作
        /// <summary>
        /// 当前操作的列（右键点击列时设置）
        /// </summary>
        private GridColumn _CurrentColumn = null;

        /// <summary>
        /// 列标题右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwTable_ColumnHeaderClick(object sender, GridColumnHeaderClickEventArgs e)
        {
            if (e.MouseEventArgs.Button == System.Windows.Forms.MouseButtons.Right)
            {
                _CurrentColumn = e.GridColumn;                
                cntMenus.SetContextMenuEx(dgrdvwTable, btnColHeader);
            }
        }

        /// <summary>
        /// 升序排列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOrderAsc_Click(object sender, EventArgs e)
        {
            if (_CurrentColumn == null) return;
            btnCancelOrder.Enabled = true;
            UpdateCursor(" order by " + _CurrentColumn.Name + " asc ");
        }

        /// <summary>
        /// 降序排列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOrderDsc_Click(object sender, EventArgs e)
        {
            if (_CurrentColumn == null) return;
            btnCancelOrder.Enabled = true;
            UpdateCursor(" order by " + _CurrentColumn.Name + " desc ");            
        }

        /// <summary>
        /// 取消排列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancelOrder_Click(object sender, EventArgs e)
        {
            btnCancelOrder.Enabled = false;
            UpdateCursor("");
        }

        /// <summary>
        /// 更新查询游标
        /// </summary>
        /// <param name="order">带order by的排序条件</param>
        /// <param name="where">查询条件</param>
        private void UpdateCursor(string order, string where = "")
        {
            if (BindTable == null) return;
            IQueryFilter flt = new QueryFilter();
            flt.WhereClause = where;
            RecordCount = BindTable.RowCount(flt);
            if (!string.IsNullOrWhiteSpace(order))
            {
                IQueryFilterDefinition def = flt as IQueryFilterDefinition;
                def.PostfixClause = order;
            }
            if (_Cursor != null)
            {
                Marshal.FinalReleaseComObject(_Cursor);
                _Cursor = null;
            }
            _Cursor = BindTable.Search(flt, false);
            _SourceAll.Clear();
            if (btnAll.Checked)
                AddAllRows();
        }

        /// <summary>
        /// 字段属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFieldAttri_Click(object sender, EventArgs e)
        {
            if (_CurrentColumn == null) return;
            if (BindTable == null ) return;
            IField fd = BindTable.Fields.get_Field(BindTable.FindField(_CurrentColumn.Name));
            if (fd == null) return;
            FrmField frm = new FrmField();
            frm.NewField = fd;
            if (frm.ShowDialog(this.GetParentForm()) != DialogResult.OK) return;
            _CurrentColumn.HeaderText = frm.NewField.AliasName;
            
        }

        /// <summary>
        /// 数值统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStaNum_Click(object sender, EventArgs e)
        {
            if (_CurrentColumn == null) return ;
            if (BindLayer == null || BindLayer.FeatureClass == null) return;
            IField fd = BindLayer.FeatureClass.Fields.get_Field(BindLayer.FeatureClass.Fields.FindField(_CurrentColumn.Name));
            if (fd.Type != esriFieldType.esriFieldTypeInteger && fd.Type != esriFieldType.esriFieldTypeSingle && fd.Type != esriFieldType.esriFieldTypeSmallInteger &&
                fd.Type != esriFieldType.esriFieldTypeDouble)
            {
                MsgHelper.ShowInfomationMsgbox("字段类型不对，该功能只能对数值字段进行统计！");
                return;
            }
            IDataStatistics dataStatistic = new DataStatisticsClass();
            ICursor cursor;
            string msg = "";
            if (((IFeatureSelection)BindLayer).SelectionSet.Count > 0)
            {
                ((IFeatureSelection)BindLayer).SelectionSet.Search(null, false, out cursor);
                msg += "选中要素";
            }
            else
            {
                cursor = BindLayer.FeatureClass.Search(null, false) as ICursor;
                msg += "所有要素";
            }
            dataStatistic.Cursor = cursor;
            dataStatistic.Field = fd.Name;
            IStatisticsResults res = dataStatistic.Statistics;
            MsgHelper.ShowInfomationMsgbox(msg + "数量：" + res.Count + ";总和：" + Math.Round(res.Sum, 3) + ";均值" + Math.Round(res.Mean, 3));
            System.Runtime.InteropServices.Marshal.ReleaseComObject(cursor);
            cursor = null;
        }
        
        /// <summary>
        /// 几何面积
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAreaCalculate_Click(object sender, EventArgs e)
        {
            if (BindLayer == null || BindLayer.FeatureClass == null) return;
            int idx = BindLayer.FeatureClass.Fields.FindField(_CurrentColumn.Name);
            IField fd = BindLayer.FeatureClass.Fields.get_Field(idx);
            if (!fd.Editable)
            {
                MsgHelper.ShowInfomationMsgbox(this.ParentForm, "该字段不能编辑");
                return;
            }
            if (MsgHelper.ShowYesOrNoQueryMsgBox("几何计算会覆盖当前列的值，是否继续？", this.ParentForm) != DialogResult.Yes) return;
            this.Cursor = Cursors.WaitCursor;
            try
            {
                IFeatureCursor pFeatCur = BindLayer.FeatureClass.Update(null, false);
                IFeature pFeature = pFeatCur.NextFeature();
                bool needConvert = false;
                int xs = 3;
                ISpatialReference spatialReference = (BindLayer.FeatureClass as IGeoDataset).SpatialReference;
                if (spatialReference != null)
                {
                    if (spatialReference is IGeographicCoordinateSystem)
                    {
                        needConvert = true;
                        xs = 7;
                    }
                }
                double scale = 0;
                Progressor pg = new Progressor();
                pg.ProgressBar = pgrsBar;
                pg.SetMaxValue(dgrdvwTable.PrimaryGrid.Rows.Count*2);
                while (pFeature != null)
                {
                    pg.Step();
                    IGeometry pGeometry = pFeature.ShapeCopy;
                    if (pGeometry.GeometryType == esriGeometryType.esriGeometryPolyline)
                    {
                        IPolyline pPolyline = pGeometry as IPolyline;
                        scale = pPolyline.Length;
                        if (needConvert)
                        {
                            IUnitConverter unitConverter = new UnitConverter();
                            scale = unitConverter.ConvertUnits(scale, esriUnits.esriDecimalDegrees, esriUnits.esriMeters);
                        }
                    }
                    else
                    {
                        IArea pArea = pGeometry as IArea;
                        if (needConvert)
                        {
                            ISpatialReference pSr = GeometryHelper.GetCGCS2000SpatialByX(pArea.Centroid.X);
                            pGeometry.Project(pSr);
                        }
                        scale = pArea.Area;
                    }
                    pFeature.set_Value(idx, Math.Round(scale, xs));
                    pFeatCur.UpdateFeature(pFeature);
                    pFeature = pFeatCur.NextFeature();
                }
                foreach (GridRow row in dgrdvwTable.PrimaryGrid.Rows)
                {
                    pg.Step();
                    IFeature feature = BindLayer.FeatureClass.GetFeature((int)row.Cells[_OIDFieldName].Value);
                    row.Cells[_CurrentColumn.Name].Value = feature.get_Value(idx);
                }
                pg.Stop();
                Marshal.ReleaseComObject(pFeatCur);
                pFeatCur = null;
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, "赋值失败，可能是数据被锁定：" + ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
            
        }

        /// <summary>
        /// 字段计算
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFieldCalculate_Click(object sender, EventArgs e)
        {
            if (_CurrentColumn == null) return;
            if (BindLayer == null || BindLayer.FeatureClass == null) return;
            int fieldIndex = BindLayer.FeatureClass.Fields.FindField(_CurrentColumn.Name);
            IField fd = BindLayer.FeatureClass.Fields.get_Field(fieldIndex);
            if ( !fd.Editable)
            {
                MsgHelper.ShowWarningMsgbox(this.ParentForm, string.Format("该字段[{0}]不支持修改！", fd.Name));
                return;
            }            
            frmFieldCalcu frm = new frmFieldCalcu(BindLayer, fieldIndex);
            if (frm.ShowDialog(this) != DialogResult.OK) return;
            try
            {
                foreach (GridRow row in dgrdvwTable.PrimaryGrid.Rows)
                {
                    IFeature feature = BindLayer.FeatureClass.GetFeature((int)row.Cells[_OIDFieldName].Value);
                    row.Cells[_CurrentColumn.Name].Value = feature.get_Value(fieldIndex);
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox(this.ParentForm, "赋值操作异常：" + ex.Message);
            }
            
        }
        
        #endregion

        /// <summary>
        /// 点击单元格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwTable_CellClick(object sender, GridCellClickEventArgs e)
        {
            e.Cancel = true;
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextPage_Click(object sender, EventArgs e)
        {
            if (_Cursor == null) return;
            btnNextPage.Enabled = false;
            try
            {
                if (btnSel.Checked) AddSelection();
                else AddAllRows();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            finally
            {
                btnNextPage.Enabled = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnJD_Click(object sender, EventArgs e)
        {
            if (_CurrentColumn == null) return;
            if (_CurrentColumn.EditorType != typeof(GridDoubleInputEditControl)) return;
            FrmText frm = new FrmText();
            frm.Title = "请设置小数位数";
            if (frm.ShowDialog() != DialogResult.OK) return;
            int jd = 2;
            if(!int.TryParse(frm.Value, out jd))
            {
                MsgHelper.ShowInfomationAlert("请设置为正整数！");
                return;
            }
            //GridDoubleInputEditControl c = _CurrentColumn.EditControl as GridDoubleInputEditControl;
            //c.DisplayFormat = string.Format("F{0}", jd.ToString());
            (_CurrentColumn.RenderControl  as GridDoubleInputEditControl).DisplayFormat= string.Format("F{0}", jd.ToString());
        }
    }
}
